package com.qfedu.dao.impl;

import com.qfedu.dao.IOrderDao;
import com.qfedu.entity.Order;
import com.qfedu.utils.JDBCUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

/**
 *  private String id;
 *     private int uid;
 *     private int aid;
 *     private int ocount;
 *     private Date otime;
 *     private int ostate;
 *     private double money;
 *     private T date;
 */
public class OrderDaoImpl implements IOrderDao {
    @Override
    public List<Order> queryOrderList(int uid) {
        try {
            return new QueryRunner(JDBCUtil.getDataSource()).query("SELECT orders.id as id,orders.aid as aid,orders.money as money,orders.ostate as ostate,orders.otime as otime,address.detail as detail,address.name as name,address.phone as phone FROM orders INNER JOIN address ON orders.uid=address.uid and orders.aid = address.id WHERE orders.uid = ?", new BeanListHandler<Order>(Order.class),uid);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }
    @Override
    public int  updateMoney(int uid,int id) {
        QueryRunner queryRunner = new QueryRunner();
        try {
            int update = queryRunner.update(JDBCUtil.getConnection(), "update orders set money = ? where uid = ? and id = ?", uid, id);
            return update;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 0;
    }

    @Override
    public int insertOrder(String id, int uid, int aid, String otime, double money) {
        QueryRunner queryRunner = new QueryRunner();
        try {
            int update = queryRunner.update(JDBCUtil.getConnection(), "insert into orders(id,uid,aid,otime,money,ostate) values (?,?,?,?,?,1)", id, uid, aid, otime, money);
            return update;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 0;
    }

    @Override
    public Order queryOrder(int id) {
        try {
            return new QueryRunner(JDBCUtil.getDataSource()).query("select * from orders where id = ?",new BeanHandler<Order>(Order.class),id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    @Override
    public Order findOrder(String oid) {
        try {
            return new QueryRunner(JDBCUtil.getDataSource()).query("select orders.id,otime,address.name as name,address.phone as phone,address.detail as detail,money from orders inner join address on address.id = orders.aid where orders.id = ?",new BeanHandler<Order>(Order.class),oid);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }
}
